package com.algernoon.nettydemo.aio.server;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable {

	private int port;
	
	CountDownLatch latch;
	
	AsynchronousServerSocketChannel asynchronousServerSocketChannel;
	
	/**
	 * 
	 * 创建一个异步的服务端通道AsynchronousServerSocketChannel，然后调用bind方法绑定监听端口
	 * 
	 * @param port
	 */
	public AsyncTimeServerHandler(int port) {
		this.port = port;
		try {
			asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
			asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
			System.out.println("The time server is start in port: " + this.port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// 完成一组正在执行的操作之前，允许当前线程一直阻塞。让线程再次阻塞，防止服务端执行完成退出
		latch = new CountDownLatch(1);
		// 接收客户端连接
		doAccept();
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 由于是异步操作，通过AcceptCompletionHandler实例接收accept操作成功的通知消息
	 * 
	 */
	private void doAccept() {
		asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());		
	}

}
